package com.shopmall.manager.listener;


import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.shopmall.manager.mapper.CategoryMapper;
import com.shopmall.model.vo.product.CategoryExcelVo;
import org.apache.poi.ss.formula.functions.T;

import java.util.List;

// 监听器
public class ExcelListener<T> implements ReadListener<T> {
    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    /**
     * 缓存的数据
     */
    private List<T> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    // 构造传递mapper，操作数据库
    private final CategoryMapper categoryMapper;

    public ExcelListener(CategoryMapper categoryMapper) {
        this.categoryMapper = categoryMapper;
    }

    @Override
    public void invoke(T t, AnalysisContext analysisContext) {
        // 把每行数据对象t放到cacheDataList集合里
        cachedDataList.add(t);
        // 达到BATCH_COUNT了，需要存储在数据中去，防止数据量过大，容易OOM
        if (cachedDataList.size() >= BATCH_COUNT) {
            // 调用方法一次性批量添加到数据库中
            saveDate();
            // 清理集合
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 数据量小于BATCH_COUNT添加到数据库中
        saveDate();
    }

    private void saveDate() {
        // 批量添加商品分类的方法
        categoryMapper.batchInsert((List<CategoryExcelVo>) cachedDataList);
    }
}
